<?php
/**
 * 支付成功通知
 */
define('NO_CHECK', true);
require_once dirname(__DIR__) . '/../../common.inc.php';

include_once BASEPATH_CONFIG . 'mobileapi/base.cfg.php';

use Center\Payment;
use Common\DataType;
use Center\User;
use Center\Goods;
use Center\CoinLog;

class notice
{
    public function doDefault()
    {
        $params = $_POST;
        $data = \lib\plugins\alipay\Alipay::rsaCheckV1($params);

        debug_log('weixin pay query productId:{} not exist user: ' . serialize($data), JF_LOG_ERROR);
        $notify_time = $_POST['notify_time']; //通知的发送时间。格式为yyyy-MM-dd HH:mm:ss
        $notify_type = $_POST['notify_type']; //通知的类型
        $notify_id = $_POST['notify_id']; //通知校验ID
        $app_id = $_POST['app_id'];
        $trade_no = $_POST['trade_no']; //支付宝交易凭证号
        $out_trade_no = $_POST['out_trade_no']; //原支付请求的商户订单号
        if (empty($trade_no) && empty($out_trade_no)) {
            exit();
        }
        //发起api请求
        $payment_info = Payment::getInfoBySN($out_trade_no);
        if (empty($payment_info)) {
            exit();
        }

        $payment_id = $payment_info['PaymentId'];
        $app_id = $payment_info['AppId'];
        $user_id = $payment_info['UserId'];
        $product_id = $payment_info['ProductId'];
        $product_info = Goods::getInfoByIds($product_id);
        if (empty($product_info)) {
            debug_log("weixin pay query productId:{$product_id} not exist user: $user_id", JF_LOG_ERROR);
            exit();
        }
        $old_status = $payment_info['Status'];
        if ($old_status == Payment::STATUS_PAY_SUCCESS) {
            echo 'success';
            exit();
        }

        $result = \lib\plugins\alipay\Alipay::tradeQuery($out_trade_no, $trade_no);
        $result = json_decode($result, true);

        $response = $result['alipay_trade_query_response'];
        if ($response['code'] == 10000) {
            $trade_status = $response['trade_status'];
            if ($trade_status == 'TRADE_CLOSED') { //未付款交易超时关闭，或支付完成后全额退款
                debug_log("alipay pay query TRADE_CLOSED, paymentId:{$payment_id}, status:{$trade_status}", JF_LOG_WARNING);
                Payment::updatePaymentBySN($out_trade_no, ['Status' => Payment::STATUS_PAY_CANCELED]);
            } elseif ($trade_status == 'TRADE_SUCCESS') { //交易支付成功
                if (Payment::isFirstPay($user_id)) {
                    CoinLog::addCoinLog($user_id, 2, CoinLog::TYPE_FIRST_PAY);
                }
                $data = [
                    'ThirdSN' => $response['trade_no'],
                    'Content' => $response['store_name'],
                    'Status' => Payment::STATUS_PAY_SUCCESS,
                    'UpdateTime' => date('Y-m-d H:i:s'),
                ];
                if (Payment::paySuccess($out_trade_no, $data) !== false) {
                    $coin = (int)$product_info['JCoin'] + (int)$product_info['Donate'];
                    pay_succ_log("paySuccess, paymentId:{$payment_id}, userId:{$user_id}");
                    if (User::updateJCoin($user_id, $coin) === false) {
                        pay_fail_log("addCoin failed, paymentId:{$payment_id}, userId:{$user_id}, Coin:{$coin}");
                        Payment::updatePaymentBySN($out_trade_no, ['Status' => Payment::STATUS_SEND_GOODS_FAILED]);
                    } else {
                        CoinLog::addCoinLog($user_id, $product_info['JCoin'], CoinLog::TYPE_EXCHANGE, false);
                        if (!empty($product_info['Donate'])) {
                            CoinLog::addCoinLog($user_id, $product_info['Donate'], CoinLog::TYPE_PAY_DONATE, false);
                        }
                        pay_succ_log("addCoin, paymentId:{$payment_id}, userId:{$user_id}, Coin:{$coin}");
                    }
                } else {
                    pay_fail_log("paySuccess failed, paymentId:{$payment_id}, uid:{$user_id}");
                }
                echo 'success';
            } elseif ($trade_status == 'TRADE_FINISHED') { //交易结束，不可退款
                debug_log("alipay notify pay query TRADE_FINISHED, paymentId:{$payment_id}, status:{$trade_status}", JF_LOG_WARNING);
            } elseif ($trade_status == 'WAIT_BUYER_PAY') { //交易创建，等待买家付款
                debug_log("alipay notify pay query faild, paymentId:{$payment_id}, status:{$trade_status}", JF_LOG_WARNING);
            }
        }
        exit;
    }
}

$app->run();
